(function($) {
  $.extend({
    getJSONP: function(url, data, cb) {
      return this.getJSON(url + '?callback=?', data, cb)
    },
    bootModal: function(title, body, size) {
      var _this = this;
      var temp = $(`
      <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog ${!!size?'modal-'+size:''}" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" role="remove" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 class="modal-title" id="myModalLabel">${title}</h4>
            </div>
            <div class="modal-body">
              ${body}
            </div>
            <div class="modal-footer">
              <button type="button" role="remove" data-dismiss="modal" class="btn btn-default">取消</button>
              <button type="button" role="submit" class="btn btn-primary">保存</button>
            </div>
          </div>
        </div>
      </div>
      `)
      temp.appendTo('body');
      temp.on('click', '[role=submit]', function() {
        temp.trigger('submit', temp)
      })
      temp.on('hidden.bs.modal', function() {
        temp.remove();
      })
      temp.show = function() {
        temp.modal('show')
        return temp;
      }
      temp.hide = function() {
        temp.modal('hide')
        return temp;
      }
      temp.toggle = function() {
        temp.modal('toggle')
        return temp;
      }
      if(temp.find('form').length>0){
        var form=temp.find('form')
        function preventEnter (event){
          if(event.keyCode==13){event.preventDefault()}
        }
        form.find('input').on('keydown',function(e){preventEnter(e)})
        form.find('textarea').on('keydown',function(e){preventEnter(e)})
        form.find('[name]').on('keydown',function(e){preventEnter(e)})
      }
      return temp;
    },
    selectPlusOptions:{
      path:'',
      method:'get',
      addPath:'',
      addMethod:'get',
      //本来是用于ajax成功后设置options的value和文本的关键字，后来发现这样并不合适
      valueKey:'id',
      textKey:'name',
      //默认 ajax请求成功时的事件，待完善      
      success:function(res,setList){
        console.log(res,setList)
      },
      //默认 加号按钮点击时的事件，待完善
      addClick:function(e,path,method){
        console.log(e,path,method);
      }
    },
    selectPlusSetup:function(obj){
      obj=obj||{};
      for (const key in $.selectPlusOptions) {
        if (obj.hasOwnProperty(key)) {
          $.selectPlusOptions[key]=obj[key];          
        }
      }
      return $.selectPlusOptions;
    },
  })
  $.fn.extend({
    serializeObject: function() {
      //当匹配到的表单数量大于1时弹出警告
      if (this.length > 1) console.warn('CH:选择器同时选中了多个表单，这可能不是你需要的状态');
      if (this.length > 1) console.warn('EN:multiply forms selected');
      var obj = {};
      $.each(this.serializeArray(), function(index) {
        //对存在多个name相同的表单元素进行处理
        if (!!obj[this['name']]) {
          if (!!!$.isArray(obj[this['name']])) {
            obj[this['name']] = [obj[this['name']]]
          }
          obj[this['name']].push(this['value'])
        } else {
          obj[this['name']] = this['value'];
        }
      });
      for (const key in obj) {
        if (obj[key]=="undefined") {
          // delete obj[key]
          obj[key]=null
        }
      }
      return obj;
    },
    inputArray: function() {
      this.each(function(index, element) {
        //获取表单元素的属性
        var _name = $(element).attr('role')
        var valStr = $(element).attr('value')
        var val = !!valStr ? JSON.parse(valStr) : [];
        var placeholder = $(element).attr('placeholder')
        var id = Math.random() * Date.now();
        if (!!$(element).attr('value')) {
          val = JSON.parse($(element).attr('value'))
          console.log(val)
        }
        if (!!!placeholder) placeholder = '';
        //展示数据      
        function showData() {
          $(element).find('p').html('');
          var subItemHtml = ``;
          //获取并展示数据
          var valStr = $(element).find('[type=hidden]').val()
          // console.log(!!valStr.trim())
          if (valStr != "undefined" && !!valStr.trim()) {
            val = JSON.parse(valStr)
          } else {
            val = [];
          };
          if (val.length != 0) {
            val.forEach(item => {
              subItemHtml += `
              <div class="btn btn-minier btn-pink" style="display:inline-flex; max-width:100%;height:auto;">
                <div role="data-item" style="display:inline-block;max-width:calc(100% - 2em);word-wrap:break-word;text-overflow: ellipsis;overflow: hidden;word-break:break-all;flex-grow:1;">
                  ${item}
                </div>
                <a  class="glyphicon glyphicon-remove" role="data-toggle" style="color:#fff; width:2em; flex-shrink:0;"></a>
              </div>
              `
            });
            $(element).find('p').html(subItemHtml)
            $(element).find('[role="data-toggle"]').on('click', function(e) {
              console.log(e)
              var targetData = $(e.target).siblings('[role="data-item"]').text().trim();
              for (var i = 0; i < val.length; i++) {
                if (val[i] == targetData) {
                  val.splice(i, 1);
                  break;
                }
              }
              $(element).find('[type=hidden]').val(JSON.stringify(val))
              $(e.target).parents('.btn').remove();
              // showData();
            })
          }
        }
        //设置数据
        function setData(data) {
          if (!!!data) return;
          if ($.inArray(data, val) == -1) {
            val.push(data)
            $(element).find('[type=hidden]').val(JSON.stringify(val))
          }
          $(element).find('textarea').val('')
        }
        //表单元素模板
        var html = `
        <input type="hidden" id="${id}" name="${_name}" value='${valStr}'/>
        <p style="width:100%"></p> 
        <textarea id="${_name}" class="form-control" placeholder="${placeholder} 回车添加 Ctrl+回车 换行" style="resize:vertical;"/></textarea>
        `
        $(element).html(html);
        $(element).css('width','100%')
        //这边的change需要手动触发
        $(element).find('[type=hidden]').on('change', function(e) {
          showData()
        })
        showData();
        //监听回车键      
        $(element).find(`textarea`).on('keyup', function(e) {
          e.preventDefault();
          if(e.ctrlKey && e.keyCode == 13){
            var val=$(element).find(`textarea`).val().split('');
            var start=$(element).find(`textarea`)[0].selectionStart;
            var end=$(element).find(`textarea`)[0].selectionEnd;
            val.splice(start,end-start,'\n')
            $(element).find(`textarea`).val(val.join(''));
            return;
          }
          if (e.keyCode == 13) {
            var regExp=new RegExp('↵')
            var val =$(this).val().replace('\r\n','\n').replace('↵','\n')
            valArr=val.split("\n")
            valArr.forEach(item => {
              setData(item)
            });
            showData();
          }
        })
      })
      return this;
    },
    selectPlus:function(successCB,addClickCB,kw){
      var _this=this;
      var kw=kw||'+'
      this.each(function(index,element){
        //获取配置
        var defOpt=$.selectPlusSetup()
        var ele=$(element);
        var name=ele.attr('role')||'';
        //数据列表来源是selectplus的list属性，指向datalist的id，或者紧跟着selectplus的datalist
        var list=!!(ele.attr('list'))?$('#'+ele.attr('list')):ele.next('datalist');
        // 配置ajax 请求的路径
        var path=!!(ele.attr('path'))?ele.attr('path'):defOpt.path;
        //配置点击添加时，ajax请求的路径
        var addPath=!!(ele.attr('a-path'))?ele.attr('a-path'):defOpt.addPath;
        //配置ajax请求的方式
        var method=!!(ele.attr('method'))?ele.attr('method'):defOpt.method;
        var addMethod=!!(ele.attr('a-method'))?ele.attr('a-method'):defOpt.addMethod;
        var valueKey=!!(ele.attr('vk'))?ele.attr('vk'):defOpt.valueKey;
        var textKey=!!(ele.attr('tk'))?ele.attr('tk'):defOpt.textKey;
        //当list的Dom节点改变时执行
        list.on('DOMSubtreeModified',function(e){
          setList();
        })
        //用于设置select部分的内容
        function setList(html){
          var template=`
          <select name="${name}" class="form-control">
          ${html||list.html()}
          </select>
          <a class="input-group-addon" role="add">${kw}</a>
          `
          ele.html(template)
          //当设置内容完成后触发ready事件
          _this.trigger('ready')
        }
        //执行ajax请求以获取数据
        function getdata(){
          if(path.trim()!=''){
            $.ajax({
              url:path,
              method:method,
              success:function(res,statu){
                if(typeof successCB =="function"){
                  successCB(res,setList)
                }else{
                  defOpt.success(res,setList);
                }
              }
            })
          }
        }
        getdata();
        //当添加按钮点击时执行
        ele.on('click','[role=add]',function(event){
          //触发addclick事件
          console.log(_this)
          _this.trigger('addClick',[addPath,addMethod,getdata]);
          if(typeof addClickCB =="function"){
            addClickCB(event,addPath,addMethod)
          }else{
            defOpt.addClick(event,addPath,addMethod);
          }
          getdata();

        })
        setList();
      })
      return _this;
    },
  })
})(jQuery)